package main

/**
给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。

示例 1:

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

分析:



链接：https://leetcode-cn.com/problems/spiral-matrix
![](http://cdn.bsummer.cn/20191103142104.png)


https://www.youtube.com/watch?v=dfGhf-Ko0L4
*/

func main() {
	a := [][]int{
		[]int{1, 2, 3},
		[]int{4, 5, 6},
		[]int{7, 8, 9},
	}
	//fmt.Println(len(a))

	spiralOrder(a)
}

func spiralOrder(matrix [][]int) []int {
	if len(matrix) == 0 {
		return []int{}
	}

	left := 0
	right := len(matrix[0]) - 1
	top := 0
	bottom := len(matrix) - 1
	ret := []int{}
	for left < right && top < bottom {
		for i := left; i < right; i++ {
			ret = append(ret, matrix[top][i])
		}

		for i := top; i < bottom; i++ {
			ret = append(ret, matrix[i][right])
		}

		for i := right; i > left; i-- {
			ret = append(ret, matrix[bottom][i])
		}

		for i := bottom; i > top; i-- {
			ret = append(ret, matrix[i][left])
		}
		left++
		right--
		top++
		bottom--
	}

	if left == right {
		for i := top; i <= bottom; i++ {
			ret = append(ret, matrix[i][left])
		}
	} else if bottom == top {
		for i := left; i <= right; i++ {
			ret = append(ret, matrix[top][i])
		}
	}

	return ret
}
